package com.web44.spring.service.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @Title: CalculatorProxy
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/1/9 14:41
 */
public class CalculatorProxy {


    /**
     *
     * @param target 要被代理的对象
     */
    public  static Object newInstance(Object target) {

        /**
         * ClassLoader loader,
         *                                           Class<?>[] interfaces,
         *                                           InvocationHandler h
         */
        ClassLoader classLoader = target.getClass().getClassLoader();

        Class<?>[] interfaces = target.getClass().getInterfaces();

        InvocationHandler invocationHandler = (proxy, method,args) -> {
            Object object =null;
            try {
                System.out.println("[日志] "+method.getName()+" 方法开始了，参数是："+ Arrays.toString(args));
                // 执行目标方法 即为执行了被代理对象的方法
                object = method.invoke(target, args);
                System.out.println("  [日志] "+method.getName()+" 方法结束了，结果是："+object);
            }catch (Throwable throwable) {
                System.out.println("[日志] "+method.getName()+" 方法开产生了异常"+ throwable.toString());
            }

            return object;

        };


        return Proxy.newProxyInstance(classLoader,interfaces,invocationHandler);
    }
}
